﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Binary
{
    public class ConditionalDeclaration : IFileDeclaration
    {
        private readonly IConditionProvider condition;
        private readonly IFileDeclaration child;

        public ConditionalDeclaration(IConditionProvider condition, IFileDeclaration child)
        {
            this.condition = condition;
            this.child = child;
        }

        public AbstractFileData Read(BinaryFileSource src, AbstractFileData parentNode)
        {
            var ret = new ConditionalData(parentNode);
            var cond = condition.GetResult(ret);
            if (cond)
            {
                ret.Data = child.Read(src, parentNode);
            }
            return ret;
        }

        public void Write(BinaryFileSource src, AbstractFileData data)
        {
            var cdata = data.As<ConditionalData>();
            if (cdata == null)
            {
                throw new WritingFormatException("Wrong data type.");
            }
            var cond = condition.GetResult(data);
            if (cond)
            {
                child.Write(src, cdata.Data);
            }
        }
    }
}
